package com.itlong.cloud.rabbitmq.consumer;

import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.property.PropertySubscriberHanlerDTO;
import com.itlong.cloud.POJO.PO.AppUserProjectPO;
import com.itlong.cloud.POJO.PO.CloudIntercomAccountInfoPO;
import com.itlong.cloud.POJO.PO.TimeTaskDeadMessageQueuePO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.app.dao.IAppUserLykzAccountDao;
import com.itlong.cloud.app.service.IAppLykzCloudIntercomAccountService;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.enumerate.AppUserProjectStatusEnum;
import com.itlong.cloud.enumerate.AppUserProjectTypeEnum;
import com.itlong.cloud.enumerate.AppUserProjectUserTypeEnum;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * <desc>
 *      云对讲SDK创建用户的灵云快智账号的消费者
 * </desc>
 *
 * @createDate 2018/11/27
 */
@Component
public class SDKUserCreateLykzAccountConsumer {

    private static final Logger LOG = LoggerFactory.getLogger(SDKUserCreateLykzAccountConsumer.class);

    @Autowired
    IAppLykzCloudIntercomAccountService iAppLykzCloudIntercomAccountService;

    @Autowired
    private IAppUserLykzAccountDao iAppUserLykzAccountDao;

    //消息队列
    @Autowired
    private MessageSender messageSender;


    /**
     * <desc>
     *      云对讲SDK创建用户的灵云快智账号的消费者
     * <desc/>
     * @param   message 消息数据
     * @author Juguang.S
     * @createDate 2018/11/27
     */
    @RabbitListener(queues = RabbitMQConstant.RABBITMQ_PROJECT_CLOUD_TALK_SDK_CREATE_LYKZ_ACCOUNT_QUEUE)
    public void process(Message message, Channel channel) throws InterruptedException,IOException {
        byte[] body = message.getBody();
        try {
            TimeTaskDeadMessageQueuePO po= JsonUtil.toObject(new String(body), TimeTaskDeadMessageQueuePO.class);
            Map<String,Object> map =  JsonUtil.toObject(po.getMessageContent(),HashMap.class);
            String phoneNum = map.get("phoneNum").toString();
            String userId = map.get("userId").toString();
            String lykzAppId = map.get("lykzAppId").toString();
            String projectId = map.get("projectId").toString();
            String lykzUserId = map.get("lykzUserId").toString();
            String newSipAccount = "";
            //LOG.info("【进入云对讲SDK创建用户】"+"userId:"+userId+"phoneNume:"+phoneNum+"lykzAppId:"+lykzAppId);
            Map<String,String> resultMap = iAppLykzCloudIntercomAccountService.getLykzCloudIntercomAccountByMoblie(phoneNum,lykzAppId);
            if(resultMap==null){
                CloudIntercomAccountInfoPO infoPO = iAppLykzCloudIntercomAccountService.createLykzCloudIntercomAccount(userId,phoneNum,lykzAppId,lykzUserId);
                if(infoPO!=null){
                    newSipAccount = infoPO.getClientUserId();
                }
            }else{
                newSipAccount = resultMap.get("lykzUserId");
                //首先根据手机号查询cloud_intercom_account_info表中是否已有该用户灵云信息数据 没有则保存
                if(iAppLykzCloudIntercomAccountService.getExistLykzInfo(resultMap.get("lykzUserId"))==0) {
                    CloudIntercomAccountInfoPO infoPO = new CloudIntercomAccountInfoPO();
                    String lykzId = LogicIdUtil.bussinessId();
                    infoPO.setCloudIntercomAccountId(lykzId);
                    infoPO.setAccountType(1);
                    infoPO.setAccount(resultMap.get("clientNumber"));
                    infoPO.setToken(resultMap.get("loginToken"));
                    infoPO.setClientPwd(resultMap.get("clientPwd"));
                    infoPO.setClientUserId(resultMap.get("lykzUserId"));
                    infoPO.setStatus(1);
                    infoPO.setAppid(lykzAppId);
                    infoPO.setCreateTime(new Date());
                    Integer result = iAppUserLykzAccountDao.save(SqlUtil.durableData(infoPO, PlatformConstants.TABLE_SAVE));
                    if (result > 0) {
                        iAppUserLykzAccountDao.updateAppUserInfo(userId, lykzId);
                    }
                }
            }

            // 处理用户项目表
            Map<String, Object> params = new HashMap<>();
            params.put("projectId", projectId);
            params.put("userId", userId);
            List<AppUserProjectPO> userProjectPOs = iAppUserLykzAccountDao.getUserProjectByParams(params);
            AppUserProjectPO userProjectPO = null;
            if (userProjectPOs == null || userProjectPOs.isEmpty()) {
                userProjectPO = new AppUserProjectPO(userId, projectId, AppUserProjectTypeEnum.USERPROJECT_TYPE_SELF.getType().toString(),
                        "000000", AppUserProjectStatusEnum.USERPROJECT_USERPROJECTSTATUS_ENABLE.getType().toString(),
                        AppUserProjectUserTypeEnum.USERPROJECT_USERTYPE_ORDINARY.getType(), DataStatusEnum.NORMAL.getType(), new Date());
                Map<String,String> result = iAppLykzCloudIntercomAccountService.getLykzCloudIntercomAccountByMoblie(phoneNum,lykzAppId);
                if(result!=null){
                    userProjectPO.setSipAccount(result.get("lykzUserId"));
                }
                String sipPsd = Md5EncryptUtil.md5(userId + phoneNum).toLowerCase();
                userProjectPO.setSipPsd(sipPsd);
                iAppUserLykzAccountDao.save(SqlUtil.durableData(userProjectPO, PlatformConstants.TABLE_SAVE));
                this.cloudSipHandler(projectId,result.get("lykzUserId"), sipPsd, null);
            } else {
                userProjectPO = userProjectPOs.get(0);
                userProjectPO.setUpdateTime(new Date());
                userProjectPO.setStatus(DataStatusEnum.NORMAL.getType());
                iAppUserLykzAccountDao.updateUserProjectInfo(userProjectPO);
            }

            //LOG.info("【云对讲SDK创建用户成功】");
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            LOG.error("【RabbitMQ_云对讲SDK创建用户的灵云快智账号业务消费端】:消费异常",e);
        } finally {
            //手动确认消息消费成功。
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }
    }

    /**
     * <desc>
     *      对sip数据源中的Sip账号进行添加，更新，或删除操作
     * <desc/>
     * @param  addOrUpdateUserName  根据userName添加或更新Sip数据源的数据（存在则更新，不存在则添加）
     * @param  addOrUpdatePassword  添加或更新Sip数据源的password
     * @param  delUserName  根据userName删除Sip数据源的数据
     * @author Biao.R
     * @createDate 2018/1/9
     */
    public void cloudSipHandler(String projectId,String addOrUpdateUserName, String addOrUpdatePassword, String delUserName) throws Exception {
        PropertySubscriberHanlerDTO subscriberHanlerDTO = new PropertySubscriberHanlerDTO(projectId,addOrUpdateUserName, addOrUpdatePassword, delUserName);
        JSONObject js = new JSONObject();
        js.put("data",JSONObject.toJSON(subscriberHanlerDTO));
        messageSender.send(RabbitMQConstant.RABBITMQ_SAVE_OR_UPDATE_SIP_QUEUE, JsonUtil.toJSON(js), RabbitMQConstant.RABBITMQ_EQUIP_EXCHANGE,
                RabbitMQConstant.RABBITMQ_SAVE_OR_UPDATE_SIP_KEY);
    }
}